import { JSONStringify, JSONParse } from './utils'
import { moduleGetList, templateGetList } from 'swagger-api/export-api/scada-config'
import { StorageEnum } from '@/enums/storageEnum'
/**
 * * 存储本地会话数据
 * @param k 键名
 * @param v 键值（无需stringiiy）
 * @returns RemovableRef
 */
export const setLocalStorage = <T>(k: string, v: T) => {
  try {
    window.localStorage.setItem(k, JSONStringify(v))
  } catch (error) {
    return false
  }
}

/**
 * * 获取本地会话数据
 * @param k 键名
 * @returns any
 */
export const getLocalStorage = (k: string) => {
  const item = window.localStorage.getItem(k)
  try {
    return item ? JSONParse(item) : item
  } catch (err) {
    return item
  }
}

/**
 * * 清除本地会话数据
 * @param name
 */
export const clearLocalStorage = (name: string) => {
  window.localStorage.removeItem(name)
}

/**
 * * 存储临时会话数据
 * @param k 键名
 * @param v 键值
 * @returns RemovableRef
 */
export const setSessionStorage = <T>(k: string, v: T) => {
  try {
    window.sessionStorage.setItem(k, JSONStringify(v))
  } catch (error) {
    return false
  }
}

/**
 * * 获取临时会话数据
 * @returns any
 */
export const getSessionStorage: (k: string) => any = (k: string) => {
  const item = window.sessionStorage.getItem(k)
  try {
    return item ? JSONParse(item) : item
  } catch (err) {
    return item
  }
}

/**
 * * 清除本地会话数据
 * @param name
 */
export const clearSessioStorage = (name: string) => {
  window.sessionStorage.removeItem(name)
}
/**
 * * 获取自定义模板和小组件数据存到缓存里
 * @param isTemp 是否是模板
 * @returns any
 */
export const getCustomizeList = async (isTemp = false) => {
  const StoreKeys = StorageEnum.GO_USER_MEDIA_CUSTOMIZE
  const StoreTempKeys = StorageEnum.GO_USER_MEDIA_TEMP
  try {
    const res = await (isTemp ? templateGetList() : moduleGetList())
    if (res.code == 0) {
      const list = res.data.map((item: any) => {
        const config = item.config ? JSON.parse(item.config) : {}
        return {
          delId: item.id,
          package: isTemp ? 'Temp' : 'Customize',
          category: isTemp ? 'Temp' : 'Customize',
          name: item.name,
          key: isTemp ? 'temp' : 'group',
          chartConfig: {
            image: item.imageUrl
          },
          ...config
        }
      })
      setLocalStorage(isTemp ? StoreTempKeys : StoreKeys, list)
      return res.data
    } else {
      setLocalStorage(isTemp ? StoreTempKeys : StoreKeys, [])
      return []
    }
  } catch (e) {
    setLocalStorage(isTemp ? StoreTempKeys : StoreKeys, [])
    return []
  }
}
